<?php

// @formatter:off
/**
 * @file WCActiveTagGarbage.php
 * @author Alejandro Dario Simi
 * @date $Date: 2014-06-03 03:40:32 +0000 (Tue, 03 Jun 2014) $
 *
 * $Id: WCActiveTagGarbage.php 112 2014-06-03 03:40:32Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/trunk/includes/activetags/WCActiveTagGarbage.php $
 */
// @formatter:on

/**
 * class WCActiveTagHook
 */
class WCActiveTagGarbage extends WCActiveTagHook {
	//
	// Public class properties.
	public static $ExpirationDates = 7;
	/**
	 * @var WCConnection Database pointer shortcut.
	 */
	protected $_db = false;
	/**
	 * @var string Database tables' prefix shortcut.
	 */
	protected $_dbprefix = false;
	//
	// Magic methods.
	public function __construct() {
		$this->_db = WCConnection::Instance();
		$this->_dbprefix = $this->_db->prefix();

		$this->_canIt["add"]["CL"] = false;
		$this->_canIt["add"]["DI"] = false;
		$this->_canIt["add"]["TA"] = false;

		$this->_canIt["remove"]["CL"] = false;
		$this->_canIt["remove"]["DI"] = false;
		$this->_canIt["remove"]["TA"] = false;

		parent::__construct();
	}
	//
	// Public methods.
	public function canBeAddedCX() {
		//
		// Setting default value to be returned.
		$out = true;
		//
		// Loading global pointers.
		global $wcProfile;
		global $wcErrno;
		global $wcError;
		//
		// Trash tag can only be added by a ORGANIZER or more.
		if(!$wcProfile->granted(WC_PERM_COMIC_TRASH)) {
			$wcErrno = 403;
			$wcError = "Tag '".WC_ACTIVE_TAG_TRASH."' access denied";
			$out = false;
		}
		//
		// Returning checks result.
		return $out;
	}
	public function canBeAddedIM() {
		//
		// Setting default value to be returned.
		$out = true;
		//
		// Loading global pointers.
		global $wcProfile;
		global $wcErrno;
		global $wcError;
		//
		// Trash tag can only be added by a ORGANIZER or more.
		if(!$wcProfile->granted(WC_PERM_IMAGE_TRASH)) {
			$wcErrno = 403;
			$wcError = "Tag '".WC_ACTIVE_TAG_TRASH."' access denied";
			$out = false;
		}
		//
		// Returning checks result.
		return $out;
	}
	public function canBeRemovedALL() {
		return $this->canBeRemovedCX() && $this->canBeRemovedIM();
	}
	public function canBeRemovedCX() {
		return $this->canBeAddedCX();
	}
	public function canBeRemovedIM() {
		return $this->canBeAddedIM();
	}
	public function hasCronTasks() {
		return true;
	}
	public function runCronTasks($spacer = "") {
		//
		// Setting default value to be returned.
		$retry = false;
		//
		// Tag shortcut.
		$tag = $this->tag();
		if($tag && $tag->ok()) {
			//
			// Group shortcut.
			$group = $tag->group();
			if($group->trash) {
				//
				// Loading trash can directory.
				$trashcan = $group->trash();
				//
				// Checking trash can directory status.
				if($trashcan && $trashcan->ok()) {
					//
					// Waking over each comic set as garbage.
					foreach($tag->comicsFull() as $comic) {
						//
						// Checking if it's already moved.
						if($comic->directory != $trashcan->id) {
							echo "{$spacer}\tMoving comic '{$comic}' to trashcan: ";

							$futurePath = WCSanitizer::SystemPath("{$trashcan->fullPath()}/{$comic->name}");
							if(!file_exists($futurePath)) {
								$comic->setDirectory($trashcan);
								if($comic->directory == $trashcan->id) {
									echo WCColorText::ShellGreen("Done")."\n";
									$retry = true;
								} else {
									echo WCColorText::ShellRed("Failed")."\n";
								}
							} else {
								echo WCColorText::ShellRed("Failed").": Path '{$futurePath}' already exists\n";
							}
						}
					}
					//
					// Waking over each image set as garbage.
					foreach($tag->imagesFull() as $image) {
						//
						// Checking if it's already moved.
						if($image->directory != $trashcan->id) {
							echo "{$spacer}\tMoving image '{$image}' into trashcan: ";
							$futurePath = WCSanitizer::SystemPath("{$trashcan->fullPath()}/{$image->name}");
							if(!file_exists($futurePath)) {
								$image->setDirectory($trashcan);
								if($image->directory == $trashcan->id) {
									echo WCColorText::ShellGreen("Done")."\n";
									$retry = true;
								} else {
									echo WCColorText::ShellRed("Failed")."\n";
								}
							} else {
								echo WCColorText::ShellRed("Failed").": Path '{$futurePath}' already exists\n";
							}
						}
					}
				}

				$this->purge($spacer);
			}
		} else {
			echo $spacer.WCColorText::ShellRed("Failed").": Tag '{$tag->name}' seems to have issues.\n";
		}

		return $retry;
	}
	//
	// Protected methods.
	protected function purge($spacer) {
		$garbage = $this->tag();

		echo "{$spacer}Purging garbage:\n";
		//
		// Creating a statement to select old comics.
		// @{
		$stmt = null;
		$stmtId = __CLASS__."::".__FUNCTION__."[comics]";
		if($this->_db->has($stmtId)) {
			$stmt = $this->_db->get($stmtId);
		} else {
			$query = "select  *\n";
			$query .= "from    {$this->_dbprefix}tag_comics\n";
			$query .= "where   mem_tag   = :garbage\n";
			$query .= " and    mem_added < (now() - interval ".self::$ExpirationDates." day)\n";
			$stmt = $this->_db->prepare($stmtId, $query);
		}
		// @}
		if($stmt->execute(array(":garbage" => $garbage->id())) && $stmt->rowCount() > 0) {
			$holder = WCComicsHolder::I();
			foreach($stmt->fetchAll() as $row) {
				$item = $holder->item($row["mem_comic"]);

				if($item && $item->ok()) {
					echo "{$spacer}\tRemoving {$item}: ";
					if($item->hardRemove()) {
						echo WCColorText::ShellGreen("Done\n");
					} else {
						echo WCColorText::ShellRed("Failed\n");
					}
				}
			}
		}
		//
		// Creating a statement to select old images.
		// @{
		$stmt = null;
		$stmtId = __CLASS__."::".__FUNCTION__."[images]";
		if($this->_db->has($stmtId)) {
			$stmt = $this->_db->get($stmtId);
		} else {
			$query = "select  *\n";
			$query .= "from    {$this->_dbprefix}tag_images\n";
			$query .= "where   mem_tag   = :garbage\n";
			$query .= " and    mem_added < (now() - interval ".self::$ExpirationDates." day)\n";
			$stmt = $this->_db->prepare($stmtId, $query);
		}
		// @}
		if($stmt->execute(array(":garbage" => $garbage->id())) && $stmt->rowCount() > 0) {
			$holder = WCImagesHolder::I();
			foreach($stmt->fetchAll() as $row) {
				$item = $holder->item($row["mem_image"]);

				if($item && $item->ok()) {
					echo "{$spacer}\tRemoving {$item}: ";
					if($item->hardRemove()) {
						echo WCColorText::ShellGreen("Done\n");
					} else {
						echo WCColorText::ShellRed("Failed\n");
					}
				}
			}
		}
	}
}
